package com.flame.core.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

public final class FileUtils {

    private FileUtils() {
    }

    public static void delete(String fileLocation) {
        if (StringUtils.hasText(fileLocation)) {
            delete(new File(fileLocation));
        }
    }

    public static void delete(File file) {
        if (!file.exists()) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null && files.length != 0) {
                for (File f : files) {
                    delete(f);
                }
            }
        }
        file.delete();
    }

    public static String md5(String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                FileInputStream fileInputStream = new FileInputStream(file);
                String md5 = DigestUtils.md5DigestAsHex(fileInputStream);
                fileInputStream.close();
                return md5;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static boolean existFile(String path) {
        return new File(path).exists();
    }

    public static String writeFile(String dirPath, String fileFullName, MultipartFile file) {
        try {
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String localFilePath = dirPath + File.separator + fileFullName;
            InputStream inputStream = file.getInputStream();
            OutputStream outputStream = new FileOutputStream(localFilePath);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return localFilePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getFileType(String fileFullName) {
        int index = fileFullName.lastIndexOf(".");
        if (index > 0) {
            return fileFullName.substring(index + 1);
        }
        return "";
    }

    public static String getFileName(String fileFullName) {
        int index = fileFullName.lastIndexOf(".");
        if (index > 0) {
            return fileFullName.substring(0, index);
        }
        return fileFullName;
    }
}
